var md5 = require('md5');
var stat = {
    /**
     * 发送上报请求
     * @param eventId   事件名称-BI定义
     * @param extraOps  额外参数，放在param里
     * @param callback  上报后的回调方法
     */
    sendRequest(eventId, pageId, extraOps) {
        try {
            let options = this.getOptions(eventId, pageId, extraOps)
            let stringSign = 'yixiaAdH5' + JSON.stringify(options)
            let sign = md5(stringSign).toString()
            this.requestAjax(sign, options)
        } catch (e) {
            console.log(e)
        }
    },
    requestAjax(sign, options) {
        let self = this
        var ajax = new XMLHttpRequest();
        ajax.open('get', '//bbadvertiserh5.bbobo.com/h5?sign=' + sign + '&data=' + window.encodeURIComponent(JSON.stringify(options)));
        ajax.send();
        ajax.onreadystatechange = function () {
            if (ajax.readyState === 4 && ajax.status === 200) {
                if (ajax.responseText !== 'ok') {
                    self.requestAjax(sign, options)
                }
            }
        }
    },
    /**
     * 获取上报参数
     * @param eventId ƒ_
     * @param extraOps 额外参数
     * @returns {{pc: string, page: string, pageId: h5页面标识, meventid: *, udid: *, param: {ua: (*|string), os: (*|others)}}}
     */
    getOptions(eventId, pageId, extraOps) {
        let envType = 1
        if (window.location.href.indexOf('yixiatong') > -1 || window.location.href.indexOf('localhost') > -1 || window.location.search.indexOf('test=1') > -1) {
            envType = 2
        }
        var options = {
            h5: 'ad-H5',
            page: pageId,
            event_type: eventId === 'h5_load' ? 1 : 2, // load || click
            udid: this._getUdid(),
            time_stamp: new Date().getTime(),
            env: envType, // 1 prod 2 test
            param: {
                ua: this.getBrowser(),
                os: this.getOs(),
                event_id: eventId,
                ...extraOps
            }
        }
        return options
    },

    S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    },
    guid() {
        return (this.S4() + this.S4() + '-' + this.S4() + '-' + this.S4() + '-' + this.S4() + '-' + this.S4() + this.S4() + this.S4());
    },

    _getUdid() {
        if (document.cookie.indexOf('SRV_H5_COOKIE_LOGIN_TOKEN') === -1) {
            let uuid = 'cms' + this.guid()
            document.cookie = 'SRV_H5_COOKIE_LOGIN_TOKEN = ' + uuid
        }
        return this.getCookie('SRV_H5_COOKIE_LOGIN_TOKEN')
    },

    getCookie(name) {
        name += '='
        var cookies = (document.cookie || '').split(';')
        var cookie = ''
        var nameLength = name.length
        var i = cookies.length
        while (i--) {
            cookie = cookies[i].replace(/^\s+/, '')
            if (cookie.slice(0, nameLength) === name) {
                return decodeURIComponent(cookie.slice(nameLength)).replace(/\s+$/, '')
            }
        }
        return ''
    },

    getOs() {
        var u = navigator.userAgent;
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
        var os = isIOS ? 'ios' : 'android';
        if (os === 'ios') return '5'
        if (os === 'android') return '6'
        var isMac = (navigator.platform === 'Mac68K') || (navigator.platform === 'MacPPC') || (navigator.platform === 'Macintosh') || (navigator.platform === 'MacIntel')
        if (isMac) return '2'
        var isUnix = (navigator.platform === 'X11') && !isWin && !isMac
        if (isUnix) return '3'
        var isLinux = (String(navigator.platform).indexOf('Linux') > -1)
        if (isLinux) return '4'
        var isWin = (navigator.platform === 'Win32') || (navigator.platform === 'Windows')
        if (isWin) return '1'
        return '7' // others
    },

    getBrowser() {
        var userAgent = navigator.userAgent.toLowerCase()
        var isOpera = userAgent.indexOf('opera') > -1
        var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('msie') > -1 && !isOpera
        var isFF = userAgent.indexOf('firefox') > -1
        var isSafari = userAgent.indexOf('safari') > -1 && userAgent.indexOf('chrome') < 1
        var isChrome = userAgent.indexOf('chrome') > -1
        if (isIE) {
            return '1'
        }
        if (isChrome) {
            return '2'
        }
        if (isFF) {
            return '3'
        }
        if (isSafari) {
            return '4'
        }
        if (isOpera) {
            return '5'
        }
        return '6'
    }
}
// tid：组件tid（曝光不要）
export default stat;
